package rjeutsky.xml.sax;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
import rjeutsky.models.OldCard;
import rjeutsky.xml.common.Constants;
import rjeutsky.xml.common.OldCardFileWriter;

public class OldCardSaxSerializer extends OldCardFileWriter {

	@Override
	public boolean deserializeFromFile() {
		try {
			SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	        Schema schema = schemaFactory.newSchema(new File(Constants.SCHEMA_PATH));
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);
			factory.setSchema(schema);
			SAXParser parser = factory.newSAXParser();						
			OldCardSaxParser handler = new OldCardSaxParser();
			FileInputStream file = new FileInputStream(filePath);
			parser.parse(file, handler);
			file.close();
			cards = handler.getCards();
			return true;
		} catch (SAXException e) {
			System.err.println(e.getMessage());
		} catch (ParserConfigurationException e) {
			System.err.println(e.getMessage());
		} catch (FileNotFoundException e){
			System.err.println(e.getMessage());
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
		return false;
	}

	@Override
	public List<OldCard> getOldCardList() {
		return cards;
	}

	@Override
	public String getInfo() {
		return "Writes with XMLStreamWriter, reads with SAX parser";
	}
	
}
